import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
	{
		path: '/',
		redirect: '/home',
	},
	{
		path: '/home',
		name: 'home',
		component: () => import('../views/Home/index.vue'),
	},
	{
		path: '/login',
		name: 'login',
		component: () => import('../views/Login/index.vue'),
	},
	{
		path: '/register',
		name: 'register',
		component: () => import('../views/Register/index.vue'),
	},
	{
		path: '/changepwd',
		name: 'changepwd',
		component: () => import('../views/Changepwd/index.vue'),
	},
	{
		path: '*',
		name: '404',
		component: () => import('../views/404NotFound.vue'),
	},
];

const router = new VueRouter({
	routes,
});
// 设置导航守卫  验证登录状态
router.beforeEach((to, from, next) => {
	// to: 将要访问的页面path
	// from: 代表从哪个路径跳转而来
	// next: 是一个函数,放行
	// next()放行 == next('/login')强制跳转

	// 如果是去注册页或者修改密码页  则直接放行  不需要验证token
	if (to.path == '/register' || to.path == '/changepwd') {
		next();
		return;
	}
	// 定义一个登录的状态
	let isLogin = localStorage.getItem('token');
	if (isLogin) {
		// 如果token存在，则需判断是否过期
		Vue.prototype.$http.post('/validate').then((res) => {
			const { code, msg } = res;
			if (code != 0) {
				// 只要不为0，就说明过期了  就需要把localStorage中的token设置为''
				window.localStorage.setItem('token', '');
				alert('用户登录已过期！！');
				next('/login');
			}
		});
		// 如果没过期则判断是否在登录页面
		if (to.path == '/login') {
			// 不需要重复登录
			next('/');
		} else {
			next();
		}
	} else {
		// 没有登录状态, 只能访问/login页面
		if (to.path != '/login') {
			alert('请先登录');
			next('/login');
		} else {
			next();
		}
	}
});

export default router;
